package org.vehicle.iface;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.vehicle.controller.ManagerInfoController;
import org.vehicle.entity.PassengerInfo;
import org.vehicle.entity.PositionInfo;
import org.vehicle.entity.TripInfo;
import org.vehicle.entity.VehicleInfo;
import org.vehicle.service.PassengerInfoService;
import org.vehicle.service.PositionInfoService;
import org.vehicle.service.TripService;
import org.vehicle.service.VehicleInfoService;
import org.vehicle.service.redis.RedisService;
import org.vehicle.util.CountDeviceProtocolHandle;
import org.vehicle.util.JsonUtils;
import org.vehicle.util.MapUtils;
import org.vehicle.vo.GCJ02_BD09;
import org.vehicle.vo.PositionAndCountInfoVO;
import org.vehicle.vo.GCJ02_BD09.Gps;

import com.fasterxml.jackson.databind.JsonNode;



@Controller
@RequestMapping("interface/position")
public class PositioninfoController {
	private static Logger logger = LogManager.getLogger(ManagerInfoController.class.getName());
	
	@Autowired
	private TripService tripService;
	@Autowired
	private PassengerInfoService passengerInfoService;
	@Autowired
	private VehicleInfoService vehicleInfoService;
	@Autowired
	private PositionInfoService positionInfoService;
	@Autowired
	private RedisService redisService;
	/**	@Autowired
	 *  上报经纬度
	 *
	 */
	@RequestMapping("/reportWarpAndWeft")
	@ResponseBody
	public Map<String, Object> reportWarpAndWeft(@RequestBody PositionAndCountInfoVO positionInfoVO){
		Map<String, Object> retMap=new HashMap<String, Object>();
		String clearCommand=null;
		String countCommand=null;
		try {
    		Gps gps=GCJ02_BD09.bd09_To_Gcj02(Double.parseDouble(positionInfoVO.getLongitude()), Double.parseDouble(positionInfoVO.getLatitude()));
    		positionInfoVO.setLatitude(gps.lat+"");
    		positionInfoVO.setLongitude(gps.lon+"");
//			synchronized(positionInfoVO.getDeviceCode()){
				Map<String, Object> paramMap=new HashMap<String, Object>();
				paramMap.put("deviceSN", positionInfoVO.getDeviceCode());
				VehicleInfo vehicleInfo=vehicleInfoService.findVehicleInfoByCode(paramMap);
	    		
	    		//根据车辆名称和开始状况1查询车辆信息
				TripInfo tripInfo=new TripInfo();
				tripInfo.setVehicleLicense(vehicleInfo.getVehicleLicense());
	    		tripInfo= tripService.findTripInfoByVehicleLicense(tripInfo);
	    		if(tripInfo!=null) {
	    		
	    		//查看是否存在该车辆信息
	    		String positionJson=redisService.getString(vehicleInfo.getVehicleLicense());
	    		JsonNode positionJsonNode=JsonUtils.fromJson(positionJson);
				String tempLogitude=null;
				String tempLatitude=null;
				if(positionJsonNode.get("logitude")!=null){
					tempLogitude=positionJsonNode.get("logitude").asText();
				}
				if(positionJsonNode.get("latitude")!=null){
					tempLatitude=positionJsonNode.get("latitude").asText();	
				}
//	    		PositionInfo tempPositionInfo=positionInfoService.getLastByTripId(tripInfo.getTripId());
	    		if(StringUtils.isEmpty(tempLogitude)&&StringUtils.isEmpty(tempLatitude)) {
	    			//添加车辆位置信息
		    		PositionInfo positionInfo=new PositionInfo();
		    		positionInfo.setTripId(tripInfo.getTripId());
		    		positionInfo.setCreateDate(new Date() );
		    		positionInfo.setLongitude(positionInfoVO.getLongitude());
		    		positionInfo.setLatitude(positionInfoVO.getLatitude());
		    		positionInfoService.insertSelective(positionInfo);
		    		Map<String, Object> positionMap=new HashMap<String, Object>();
		    		positionMap.put("tripId", tripInfo.getTripId());
		    		positionMap.put("logitude", positionInfoVO.getLongitude());
					positionMap.put("latitude", positionInfoVO.getLatitude());
					positionMap.put("state", 2);
		    		redisService.setString(vehicleInfo.getVehicleLicense(), JsonUtils.toJson(positionMap));
	    		}else {
	    			
					Double startlongitude =Double.parseDouble(tempLogitude);
					Double startlatitude = Double.parseDouble(tempLatitude);
					Double endlongitude =Double.parseDouble(positionInfoVO.getLongitude());
					Double endlatitude =Double.parseDouble(positionInfoVO.getLatitude());
					double distance = MapUtils.GetDistance(startlongitude, startlatitude, endlongitude, endlatitude);
					if(distance>100) {
						//添加车辆位置信息
						PositionInfo positionInfo=new PositionInfo();
			    		positionInfo.setTripId(tripInfo.getTripId());
			    		positionInfo.setCreateDate(new Date() );
			    		positionInfo.setLongitude(positionInfoVO.getLongitude());
			    		positionInfo.setLatitude(positionInfoVO.getLatitude());
			    		positionInfoService.insertSelective(positionInfo);
			    		Map<String, Object> positionMap=new HashMap<String, Object>();
			    		positionMap.put("tripId", tripInfo.getTripId());
			    		positionMap.put("logitude", positionInfoVO.getLongitude());
						positionMap.put("latitude", positionInfoVO.getLatitude());
						positionMap.put("state", 2);
			    		redisService.setString(vehicleInfo.getVehicleLicense(), JsonUtils.toJson(positionMap));
					}
				}
	    		retMap.put("state", 1);
				retMap.put("msg","信息添加");
	    		Long stopPassengerId = tripInfo.getStopPassengerId();
	    		//查询客运站位置
	    			PassengerInfo passengerInfo=passengerInfoService.selectByPrimaryKey(stopPassengerId);
					Double longitude =Double.parseDouble(passengerInfo.getLongitude());
					
					Double latitude =Double.parseDouble(passengerInfo.getLatitude());
					
	    			Double startlongitude =Double.parseDouble(positionInfoVO.getLongitude());
	 				
	 				Double startlatitude = Double.parseDouble(positionInfoVO.getLatitude());
	 				double distance = MapUtils.GetDistance( longitude, latitude,startlongitude, startlatitude);
	 				if(distance<300) {
	 		    		retMap.put("state", 2);
	 					retMap.put("msg","行程即将结束");
	 				}
	 				String command=redisService.getString(vehicleInfo.getVehicleLicense()+"_command");
	 				if("1".equals(command)){
	 					clearCommand=CountDeviceProtocolHandle.getClearCommand();
	 					redisService.removeString(vehicleInfo.getVehicleLicense()+"_command");
	 				}else{
	 					countCommand=CountDeviceProtocolHandle.getCountCommand();
	 				}
	    		 }else {
	    			retMap.put("state", 0);
	    			retMap.put("msg","该车辆未行驶");
				}
//			}
		} catch (Exception e) {
			logger.error(e);
			retMap.put("state", 0);
			retMap.put("msg","信息暂且没有");
		}
		retMap.put("clearCommand", clearCommand);
		retMap.put("countCommand", countCommand);
		return retMap;
	}

	/**	@Autowired
	 *  上报计数器设备
	 *
	 */
	@RequestMapping("/reportCount")
	@ResponseBody
	public Map<String, Object> reportCount(@RequestBody PositionAndCountInfoVO countInfoVO){
		logger.trace(countInfoVO.getCountDeviceData());
		Map<String, Object> retMap=new HashMap<String, Object>();
			try {
    		Map<String, Object> paramMap=new HashMap<String, Object>();
			paramMap.put("deviceSN", countInfoVO.getDeviceCode());
			VehicleInfo vehicleInfo=vehicleInfoService.findVehicleInfoByCode(paramMap);
    		
    		//根据车辆名称和开始状况1查询车辆信息
			TripInfo tripInfo=new TripInfo();
			tripInfo.setVehicleLicense(vehicleInfo.getVehicleLicense());
    		tripInfo= tripService.findTripInfoByVehicleLicense(tripInfo);
    		if(tripInfo!=null) {
    			if(vehicleInfo.getVehicleType()==1){
    				String positionJson=redisService.getString(vehicleInfo.getVehicleLicense());
        			positionJson=vehicleInfoService.updatePersonCount(vehicleInfo, countInfoVO.getCountDeviceData(), positionJson);
            		redisService.setString(vehicleInfo.getVehicleLicense(), positionJson);
    			}
    			retMap.put("state", 1);
    			retMap.put("msg","操作成功");
    		}else {
    			retMap.put("state", 0);
    			retMap.put("msg","该车辆未行驶");
			}
		} catch (Exception e) {
			logger.error(e);
			retMap.put("state", 0);
			retMap.put("msg","信息暂且没有");
		}
		return retMap;
	}
}
